package com.example.webchar.webchar.controller;

import com.example.webchar.webchar.pojo.Users;
import com.example.webchar.webchar.service.serverimpl.CrawlImpl;
import com.example.webchar.webchar.utils.JwtUtil;
import com.example.webchar.webchar.utils.RedisUtils;
import com.example.webchar.webchar.utils.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;


/**
 * @program: webchars
 * @description
 * @author: 毛叶贵子 /
 * //爬虫
 * @create: 2021-08-22 02:46
 **/
@CrossOrigin
@RestController
@RequestMapping("/crawl")
public class JsoupController {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private CrawlImpl crawl;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 根据小说名称爬取小说信息
     *
     * @param name 小说名称
     * @return
     */

    @GetMapping("/crawl/{name}")
    public Result crawl(@PathVariable String name) {
        if (name != null) {
            String token = JwtUtil.subStringToken(request);
            Users user = (Users) redisUtils.get(token);
            HashMap<String, String> hashMap = new HashMap<>(4);
            //hashMap的扩容机制 在3/4时会扩容
            hashMap.put("name", name);
            hashMap.put("email", user.getEmail());
            //获取当前用户信息
            this.rabbitTemplate.convertAndSend("novel", hashMap);
            return Result.success().add("success", "您选择的小说已添加，请您关注后续添加信息");
        } else {
            return Result.fail().add("err", "请输入相应的小说");
        }
    }

    /**
     * 换源爬取小说
     *
     * @param name 小说名称
     * @return
     */
    @GetMapping("/craw/changeTheSource/{name}")
    public Result crawChangeTheSource(@PathVariable("name") String name) {
        crawl.novelCrawlChangeTheSource(name);
        return name.equals(null) ? Result.fail().add("err", "请输入小说id") : Result.success().add("success", "成功");
    }
}
